package com.prig.base.shiro;

import cn.hutool.core.util.StrUtil;
import com.prig.base.entity.Permission;
import com.prig.base.service.PermissionService;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class ShiroConfig {
    private PermissionService permissionService;
    @Autowired
    public void setPermissionService(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Bean
    public Realm realm(){
        return new UserRealm();
    }

    @Bean
    public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){

        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setUsePrefix(true);

        return defaultAdvisorAutoProxyCreator;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition(){
        //anon 随意访问 authc 登陆访问
        DefaultShiroFilterChainDefinition  chain = new DefaultShiroFilterChainDefinition();
        List<Permission> permissions = permissionService.getPermissionsIsViewIsTrue();
        permissions.forEach(x->{
                    if(StrUtil.isNotBlank(x.getUrl())){
                        chain.addPathDefinition(x.getUrl(),"perms["+x.getUrl()+"]");
                    }
                }
                );
//        chain.addPathDefinition("/role/getRoleList","authc,");
//        chain.addPathDefinition("/**","anon");

//        chain.addPathDefinition("/templates/role/**","roles[ss]");
        return chain;
    }
}
